import AudioMgr from "../../common/audio/AudioMgr";
import { EventMessage } from "../../common/config/EventMessageConfig";
import { LayerID } from "../../common/config/GameUIConfig";
import { net } from "../../common/net/HttpRequest";
import { UIManager } from "../../common/ui/UIManager";
import { GameManager } from "./GameManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class loading extends cc.Component {

    @property(cc.Node)
    toast: cc.Node = null;

    start() {
        GameManager.getInstance().ui = new UIManager(this.node);
        AudioMgr.instance.playBGM("bgm");

        GameManager.getInstance().gameData.token = localStorage.getItem('ahxmgk-manage-token');
        GameManager.getInstance().gameData.user = JSON.parse(localStorage.getItem('ahxmgk-manage-user'))

        if (!GameManager.getInstance().gameData.token) {
            if (!GameManager.getInstance().gameData.isDug) {
                let targetUrl = '/dati/3vAtHpVM3E7YtjZQlBCk';
                window.location.href = targetUrl;
            }
        }
        cc.resources.loadDir("prefab", cc.Prefab, (err) => {
            if (err) {
                console.error(err);
            } else {
                // GameManager.getInstance().ui.openView(LayerID.game);
            }
        });
        if (GameManager.getInstance().gameData.isDug) {
            net.httpPost("https://dati.api.anhuiyun.com/api/wechat/testTokenToken", { q: "3vAtHpVM3E7YtjZQlBCk", app: "dt" }
            ).then((data: any) => {
                console.log(data)
                data = JSON.parse(data);
                console.log(data)
                GameManager.getInstance().gameData.token = data.data.access_token;
                GameManager.getInstance().gameData.user = data.data.user;
            });
        }
        if (GameManager.getInstance().gameData.user) {
            GameManager.getInstance().gameData.gameNum = GameManager.getInstance().gameData.user.number;
        }


        GameManager.getInstance().message.on(EventMessage.GAME_MESSAGE, this.message, this);

    }

    toastSchu = null;
    message() {
        this.toast.active = true;
        this.toast.getChildByName("desc").getComponent(cc.Label).string = GameManager.getInstance().gameData.gameMessage;
        this.unschedule(this.toastSchu);
        this.toastSchu = () => {
            this.toast.active = false;
        }
        this.scheduleOnce(this.toastSchu, 3)
    }

    beginGame() {
        GameManager.getInstance().ui.openView(LayerID.game);
    }

    rule() {
        GameManager.getInstance().ui.openView(LayerID.gameRule);
    }

    // update (dt) {}
}
